<script setup lang="ts">
  import { ref, watch } from 'vue';
  import TableLayout from '@/layout/table-layout.vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { useForm } from '@/hooks/arco/useForm';
  import {
    queryProducts,
    createProduct,
    updateProduct,
    deleteProduct,
    queryUnits,
  } from '@/api/reemployment-management/product';
  import DetailDrawer from '@/components/detail-drawer/index.vue';
  import useDetailDrawerBinder from '@/hooks/arco/useDetailDrawerBinder';

  const loading = ref(false);
  const baseNameMap = {
    itemId: { key: 'id', label: '项目ID' },
    itemName: { key: 'name', label: '项目名称', placeholder: '请输入项目名称' },
    itemUnitCode: {
      key: 'unitCode',
      label: '计量单位',
      placeholder: '请选择计量单位',
    },
    itemUnitName: {
      key: 'unitName',
      label: '计量单位',
      placeholder: '请选择计量单位',
    },
    itemPrice: { key: 'price', label: '单价（元）', placeholder: '请输入单价' },
    btnActionTitle: { label: '操作' },
    btnAction: { label: '查看' },
  };

  const dataPage = ref({
    total: 0,
    page: 1,
    pageSize: 10,
  });

  // 查询表格列配置
  const tableColumns = [
    {
      title: baseNameMap.itemId.label,
      dataIndex: baseNameMap.itemId.key,
      // width: 350,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.itemName.label,
      dataIndex: baseNameMap.itemName.key,
      // width: 350,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: baseNameMap.itemUnitName.label,
      dataIndex: baseNameMap.itemUnitName.key,
      // width: 350,
    },
    {
      title: baseNameMap.itemPrice.label,
      dataIndex: baseNameMap.itemPrice.key,
      // width: 160,
    },
    {
      title: baseNameMap.btnActionTitle.label,
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right',
      width: 100,
    },
  ];

  const unitOptions = useSelectOption({
    apiFun: queryUnits,
    fieldNames: {
      label: 'name',
      value: 'code',
    },
  });

  const currentUnitName = ref('');

  const pageTable = usePageTable({
    resetBtn: false,
    searchForm: {
      state: {
        [baseNameMap.itemName.key]: '',
      },
    },
    table: {
      rowKey: baseNameMap.itemId.key,
      fakePage: true,
      apiFun: async (query) => {
        return new Promise((resolve) => {
          const params = {
            ...dataPage.value,
            [baseNameMap.itemName.key]: query[baseNameMap.itemName.key],
          };
          queryProducts(params)
            .then((res) => {
              dataPage.value.total = res.total;
              resolve(res.list);
            })
            .catch((err) => {})
            .finally(() => {});
        });
      },
      onSuccess(data) {
        // dataDepartments.value = getDepartmentList(data);
      },
      columns: tableColumns,
    },
  });

  const currentItem = useForm({
    state: {
      [baseNameMap.itemId.key]: '',
      [baseNameMap.itemName.key]: '',
      [baseNameMap.itemUnitCode.key]: '',
      [baseNameMap.itemPrice.key]: 0,
    },
    rules: {
      [baseNameMap.itemName.key]: {
        required: true,
        message: baseNameMap.itemName.placeholder,
      },
      [baseNameMap.itemUnitCode.key]: {
        required: true,
        message: baseNameMap.itemUnitCode.placeholder,
      },
      [baseNameMap.itemPrice.key]: {
        required: true,
        message: baseNameMap.itemPrice.placeholder,
      },
    },
  });

  const detailDrawerHandler = useDetailDrawerBinder({
    modes: ['detail', 'add', 'edit'] as const,
    renderTitle: (mode) => (mode === 'add' ? '新增项目' : '项目详情'),
    modalName: '项目',
    deleteText: '提示：此操作不可逆，删除后将无法恢复。',
    onShow(mode, otherParams) {
      if (mode === 'add') {
        currentItem.backToInit();
        currentUnitName.value = '';
      } else {
        otherParams[baseNameMap.itemPrice.key] = parseFloat(
          otherParams[baseNameMap.itemPrice.key]
        );
        currentItem.setFieldsValue(otherParams);
      }
    },
    async onOkClick(mode) {
      await currentItem.validate();
      loading.value = true;
      const data = {
        [baseNameMap.itemName.key]: currentItem.state[baseNameMap.itemName.key],
        [baseNameMap.itemUnitCode.key]:
          currentItem.state[baseNameMap.itemUnitCode.key],
        [baseNameMap.itemPrice.key]:
          currentItem.state[baseNameMap.itemPrice.key],
      };
      if (mode === 'add') {
        return createProduct(data);
      }
      data[baseNameMap.itemId.key] = currentItem.state[baseNameMap.itemId.key];
      return updateProduct(data);
    },
    deleteApi: () => {
      loading.value = true;
      return deleteProduct(currentItem.state[baseNameMap.itemId.key] as string);
    },
    onHide(mode) {
      if (loading.value) {
        pageTable.reload();
        loading.value = false;
      }
    },
  });

  watch(()=>currentItem.state[baseNameMap.itemUnitCode.key], (newVal)=>{
    unitOptions.bindProps.options.forEach((option: any)=>{
      if (option.value === currentItem.state[baseNameMap.itemUnitCode.key]) {
        currentUnitName.value = option.label;
      }
    });
  });
</script>

<template>
  <div class="m-project">
    <TableLayout
      v-bind="pageTable.bindProps"
      @create="detailDrawerHandler.showModal('add')"
    >
      <template #searchForm="{ state }">
        <!-- 项目名称 -->
        <a-form-item
          :field="baseNameMap.itemName.key"
          :label="baseNameMap.itemName.label"
        >
          <a-input
            v-model="state[baseNameMap.itemName.key]"
            :placeholder="baseNameMap.itemName.placeholder"
            allow-clear
          />
        </a-form-item>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button
            size="small"
            type="text"
            @click="detailDrawerHandler.showModal('detail', record)"
            >{{ baseNameMap.btnAction.label }}</a-button
          >
        </a-space>
      </template>
    </TableLayout>
    <DetailDrawer v-bind="detailDrawerHandler.bindProps">
      <template #default>
        <a-form
          v-bind="currentItem.bindProps"
          layout="vertical"
          :disabled="detailDrawerHandler.modeIs('detail')"
        >
          <a-form-item
            :field="baseNameMap.itemName.key"
            :label="baseNameMap.itemName.label"
            required
          >
            <a-input
              v-model="currentItem.state[baseNameMap.itemName.key]"
              :placeholder="baseNameMap.itemName.placeholder"
            />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.itemUnitCode.key"
            :label="baseNameMap.itemUnitCode.label"
            required
          >
            <a-select
              v-bind="unitOptions.bindProps"
              v-model="currentItem.state[baseNameMap.itemUnitCode.key]"
              :placeholder="baseNameMap.itemUnitCode.placeholder"
            />
          </a-form-item>
          <a-form-item
            :field="baseNameMap.itemPrice.key"
            :label="baseNameMap.itemPrice.label"
            required
          >
            <a-input-number
              v-model="currentItem.state[baseNameMap.itemPrice.key]"
              :min="0"
              :precision="3"
              :placeholder="baseNameMap.itemPrice.placeholder"
            >
              <template #append>
                <span v-if="unitOptions.bindProps.options"
                  >{{ currentUnitName?  currentUnitName: '/'}}</span
                >
              </template>
            </a-input-number>
          </a-form-item>
        </a-form>
      </template>
    </DetailDrawer>
  </div>
</template>

<style lang="less" scoped></style>
